<!DOCTYPE html>
<html lang="zh-cn">
<head>
    <meta charset="UTF-8">
    <title>台球</title>
</head>
<body>
<canvas id="myCanvas" width="847" height="440" style="border: 1px solid #c3c3c3; background-color: #000">
    糟糕 你的浏览器 我还搞不懂也？
</canvas>
<script>
    let myCanvas = document.getElementById("myCanvas");
    let cxt = myCanvas.getContext("2d");
    let r = 20;
    let balls = [];

    // 随机色获取
    let randomColor = function () {
        let arrHex = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'];
        let strHex = "#";
        let index;
        for (let i = 0; i < 6; i++) {
            index = Math.round(Math.random() * 15);
            strHex += arrHex[index];
        }
        return strHex;
    }

    /**
     * 初始化台球位置信息
     */
    let initBall = function () {
        // 顶点的白球
        let parentBall = {
            position: {x: 200, y:200},
            r: r,
            color: "#fff"
        };
        // 开始位置
        let firstBall = {
            position: {x: 550, y:200},
            r: r,
            color: randomColor()
        };
        for (let j = 1; j < 5; j++) {
            for (let k = 0; k < (j + 1); k++) {
                let ball = {
                    position: {
                        x: firstBall.position.x + j * Math.sqrt(3) * r,
                        y: firstBall.position.y - j * r + 2 * k * r
                    },
                    r: r,
                    color: randomColor()
                };
                balls.push(ball);
            }
        }
        balls.push(firstBall);
        balls.push(parentBall);
    }

    // 绘制圆形
    let draw = function () {
        for (let i in balls) {
            cxt.fillStyle = balls[i].color;
            cxt.beginPath();
            cxt.arc(
                balls[i].position.x,
                balls[i].position.y,
                balls[i].r, 0, Math.PI * 2, true);
            cxt.closePath();    // 关闭路径
            cxt.fill();         // 使用指定颜色、渐变或模式来绘制或填充当前路径的内部。
        }
    }
    initBall();
    draw();

</script>
</body>
</html>